import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { useStorage } from '@/hooks/useStorage'
import { Cart } from '@/types/cart'

const storage = useStorage()
const CART_KEY = 'cart'

const cartSlice = createSlice({
  name: 'cart',
  initialState: (storage.getStorage(CART_KEY) as { cartList: Cart[] }) || {
    cartList: []
  },
  reducers: {
    // 加入购物车
    setCartList (state, action: PayloadAction<Cart>) {
      const filterList = state.cartList.find(
        item => item.id === action.payload.id
      )
      if (filterList) {
        filterList.number += action.payload.number
      } else {
        state.cartList.push(action.payload)
      }
      storage.setStorage(CART_KEY, state)

      return state
    },

    // 改变单个选中状态
    setChecked (state, action: PayloadAction<{ checked: boolean; id: string }>) {
      const filterList = state.cartList.find(
        item => item.id === action.payload.id
      )
      if (filterList) {
        filterList.isChecked = action.payload.checked
      }
      storage.setStorage(CART_KEY, state)

      return state
    }, // 全选反选
    setAllChecked (state, action: PayloadAction<{ checked: boolean }>) {
      state.cartList.forEach((item: Cart) => {
        item.isChecked = action.payload.checked
      })
      storage.setStorage(CART_KEY, state)

      return state
    },

    // 改变数量
    setNum (state, action: PayloadAction<{ num: number; id: string }>) {
      const filterList = state.cartList.find(
        item => item.id === action.payload.id
      )
      if (filterList) {
        filterList.number = action.payload.num
      }
      storage.setStorage(CART_KEY, state)

      return state
    },

    // 删除商品
    del (state, action: PayloadAction<{ id: string }>) {
      const filterList = state.cartList.filter(
        item => item.id != action.payload.id
      )
      if (filterList) {
        state.cartList = filterList
      }
      storage.setStorage(CART_KEY, state)
      return state
    }
  }
})

export const { setCartList, setChecked, setNum, del, setAllChecked } =
  cartSlice.actions

export default cartSlice.reducer
